/*
 *  您可以更改此项目但请不要删除作者署名谢谢，否则根据中华人民共和国版权法进行处理.
 *  You may change this item but please do not remove the author's signature,
 *  otherwise it will be dealt with according to the Copyright Law of the People's Republic of China.
 *
 *  如果需要联系到我请加Wechat: yangbuyiya 备注交流学习
 *  If you need to contact me, please add Wechat: yangbuyiya as a note to exchange and learn.
 *  yangbuyi Copyright (c) https://yby6.com 2024.
 */

package com.yby6.utils;


import cn.hutool.core.util.IdUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tts.v20190823.TtsClient;
import com.tencentcloudapi.tts.v20190823.models.TextToVoiceRequest;
import com.tencentcloudapi.tts.v20190823.models.TextToVoiceResponse;
import com.yby6.config.TencentConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * 语音合成 - 工具类
 *
 * @author Yang Shuai
 * Create By 2024/06/15
 */
@Slf4j
public class TtsUtils {
    /**
     * 匹配是否存在URL存在则移除
     */
    private final static String urlPattern = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\\\(\\\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+";
    // 匹配所有的全角标点符号 ，。
    private final static String fullAnglePattern = "[！？【】（）％＃＠＆「」『』]";
    // 匹配所有的emoji符号
    private final static String emojiPattern = "[\\uD83C\\uDF00-\\uD83D\\uDDFF" +
            "\\uD83E\\uDD00-\\uD83E\\uDDFF" +
            "\\uD83D\\uDE00-\\uD83D\\uDE4F" +
            "\\uD83D\\uDE80-\\uD83D\\uDEFF" +
            "\\u2600-\\u26FF\\u2700-\\u27BF]+";

    private static final Credential credential = initCredential();
    private static final TtsClient client = initClient();
    
    /**
     * 初始化凭证
     *
     * @return {@link Credential}
     */
    private static Credential initCredential() {
        TencentConfig instance = TencentConfig.getInstance();
        return new Credential(instance.getSecretId(), instance.getSecretKey());
    }
    
    /**
     * 初始化请求客户端
     *
     * @return {@link TtsClient}
     */
    private static TtsClient initClient() {
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("tts.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new TtsClient(credential, "ap-shanghai", clientProfile);
    }

    /**
     * TTS 语音合成
     *
     * @param text 文本
     * @return {@link String}
     */
    public static String textToVoice(String text) {
        log.info("开始TTS语音合成:{}", text);
        TextToVoiceRequest req = new TextToVoiceRequest();
        req.setEnableSubtitle(true);
        req.setText(text.replaceAll(urlPattern, "")
                .replaceAll(fullAnglePattern, "")
                .replaceAll(emojiPattern, "")
        );
        req.setSessionId(IdUtil.nanoId());
        req.setVoiceType(301032L);
        req.setCodec("mp3");
        req.setEmotionCategory("happy");
        
        try {
            TextToVoiceResponse resp = client.TextToVoice(req);
            log.info("Request ID: {}", resp.getRequestId());
            // 返回的是Base64
            return "data:audio/mp3;base64," + resp.getAudio();
        } catch (TencentCloudSDKException e) {
            log.error("【腾讯云语音合成接口调用异常】", e);
            //throw new RuntimeException("腾讯云语音合成接口调用异常", e);
        }
        return "";
    }
}
